package com.yuanchu.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanchu.common.exception.YuanChuException;
import com.yuanchu.common.utils.DateFormatUtils;
import com.yuanchu.common.utils.PageResult;
import com.yuanchu.order.client.FeignStoreClient;
import com.yuanchu.order.dao.YoshopOrderRefundDao;
import com.yuanchu.order.dao.YoshopOrderRefundImageDao;
import com.yuanchu.order.dao.YoshopRegionDao;
import com.yuanchu.order.dto.GoodsRefundParamsDto;
import com.yuanchu.order.dto.OrderDetailDto;
import com.yuanchu.order.dto.OrderRefundParamsDto;
import com.yuanchu.order.entity.*;
import com.yuanchu.order.searchconfig.MqOrderConstants;
import com.yuanchu.order.service.YoshopOrderGoodsService;
import com.yuanchu.order.service.YoshopOrderRefundAddressService;
import com.yuanchu.order.service.YoshopOrderRefundService;
import com.yuanchu.order.service.YoshopOrderService;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.Instant;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @version: 1.0
 * @Author: adan
 * @description: 订单售后
 * @date: 2024-01-24 16:50
 */
@Service
public class YoshopOrderRefundServiceImpl extends ServiceImpl<YoshopOrderRefundDao, YoshopOrderRefundEntity> implements YoshopOrderRefundService {

    @Resource
    private FeignStoreClient feignStoreClient;

    @Resource
    private YoshopOrderService yoshopOrderService;
    @Resource
    private YoshopOrderRefundAddressService orderRefundAddressService;
    @Resource
    private YoshopRegionDao regionDao;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private YoshopOrderRefundImageDao orderRefundImageDao;
    @Resource
    private YoshopOrderGoodsService orderGoodsService;

    @Override
    public long queryRefundOrder() {
        return this.count(new QueryWrapper<YoshopOrderRefundEntity>().eq("status", 0));
    }

    @Override
    public PageResult<YoshopOrderRefundEntity> queryRefundOrder(Integer state, Integer page, Integer userId) {
        if (userId == null) {
            return null;
        }
        LambdaQueryWrapper<YoshopOrderRefundEntity> lqw = new LambdaQueryWrapper<>();
        lqw.eq(YoshopOrderRefundEntity::getUserId, userId);
        if (state == 0) {
            // 待处理（audit_status == 0）
            lqw.eq(YoshopOrderRefundEntity::getStatus, 0);
        }

        // 全部
        Page<YoshopOrderRefundEntity> page1 = new Page<>(page, 15);
        Page<YoshopOrderRefundEntity> page_result = this.page(page1, lqw);
        List<YoshopOrderRefundEntity> collect = page_result.getRecords().stream().map(orderGoods -> {
            formatOrderRefund(orderGoods);
            return orderGoods;
        }).sorted(Comparator.comparing(YoshopOrderRefundEntity::getCreateTime).reversed()).collect(Collectors.toList());

        PageResult<YoshopOrderRefundEntity> result = new PageResult<>();
        result.setTotal(Math.toIntExact(page_result.getTotal()));
        result.setCurrentPage(page);
        result.setData(collect);
        result.setPerPage(15);
        long total = page_result.getTotal();
        // 计算总页数，向下取整避免超出实际页数（这里已假设pageInfo.getTotal()返回的是long类型）
        int totalPages = (int) Math.ceil((double) total / 15);
        result.setLastPage(totalPages);

        return result;
    }

    @Override
    public YoshopOrderRefundEntity queryRefundOrderDetail(Integer userId, Integer orderRefundId) {
        YoshopOrderRefundEntity orderRefund = this.getById(orderRefundId);
        if (orderRefund == null) {
            return null;
        }
        formatOrderRefund(orderRefund);
        if (orderRefund.getAuditStatus() == 10){
            // 同意退货，设置商家地址
            YoshopOrderRefundAddressEntity orderRefundAddress = orderRefundAddressService.getOne(new QueryWrapper<YoshopOrderRefundAddressEntity>()
                    .eq("order_refund_id", orderRefundId));
            Integer regionId = orderRefundAddress.getRegionId();
            Map<String, Object> region = regionDao.getAddressByOrderId(regionId);
            orderRefundAddress.setRegion(region);
            orderRefund.setAddress(orderRefundAddress);
        }
        if (orderRefund.getIsUserSend() == 1){
            // 用户已发货
            YoshopExpressEntity express = feignStoreClient.queryExpressById(Integer.valueOf(orderRefund.getExpressId()));
            express.setCreateTime(DateFormatUtils.formatDatetime(express.getCreateTime()));
            orderRefund.setExpress(express);
        }
        return orderRefund;
    }
    @Override
    public YoshopOrderRefundEntity getRefund(Integer orderId, Integer orderGoodsId) {
        YoshopOrderRefundEntity orderRefund = this.getOne(new QueryWrapper<YoshopOrderRefundEntity>().eq("order_goods_id", orderGoodsId).eq("order_id", orderId));
        if (orderRefund == null) {
            return null;
        }
        formatOrderRefund(orderRefund);
        return orderRefund;
    }

    @Override
    public YoshopOrderRefundEntity queryRefundOrderDetail(Integer orderRefundId) {
        YoshopOrderRefundEntity orderRefund = this.getById(orderRefundId);
        if (orderRefund == null) {
            return null;
        }
        formatOrderRefund(orderRefund);
        if (orderRefund.getAuditStatus() == 10){
            // 同意退货，设置商家地址
            YoshopOrderRefundAddressEntity orderRefundAddress = orderRefundAddressService.getOne(new QueryWrapper<YoshopOrderRefundAddressEntity>()
                    .eq("order_refund_id", orderRefundId));
            Integer regionId = orderRefundAddress.getRegionId();
            Map<String, Object> region = regionDao.getAddressByOrderId(regionId);
            orderRefundAddress.setRegion(region);
            orderRefund.setAddress(orderRefundAddress);
        }
        orderRefund.setUser(feignStoreClient.queryUserByUserId(orderRefund.getUserId()));
        OrderDetailDto orderDetail = yoshopOrderService.getStoreOrderDetail(orderRefund.getOrderId(), 10001);
        YoshopOrderEntity orderEntity = new YoshopOrderEntity();
        BeanUtils.copyProperties(orderDetail, orderEntity);
        orderEntity.setGoods(null);
        orderRefund.setOrderData(orderEntity);
        return orderRefund;
    }

    @Override
    @Transactional
    public void auditOrderRefund(OrderRefundParamsDto param) {
        Integer orderRefundId = param.getOrderRefundId();
        YoshopOrderRefundEntity orderRefund = this.getById(orderRefundId);
        if (orderRefund == null) {
            throw new YuanChuException("售后订单不存在");
        }
        // 是否同意
        if (orderRefund.getAuditStatus() == 10) {
            // 同意退货，设置商家地址
            YoshopStoreAddressEntity storeAddress = feignStoreClient.queryStoreAddress(param.getForm().getAddressId());
            if (storeAddress == null){
                throw new YuanChuException("售后订单地址不存在");
            }
            YoshopOrderRefundAddressEntity orderRefundAddress = orderRefundAddressService.getOne(new QueryWrapper<YoshopOrderRefundAddressEntity>().eq("order_refund_id", orderRefundId));
            if (orderRefundAddress == null){
                orderRefundAddress = new YoshopOrderRefundAddressEntity();
                orderRefundAddress.setOrderRefundId(orderRefundId);
                BeanUtils.copyProperties(storeAddress, orderRefundAddress);
                orderRefundAddress.setCreateTime(String.valueOf(Instant.now().toEpochMilli() / 1000));
                boolean save = orderRefundAddressService.save(orderRefundAddress);

                if (!save) {
                    throw new YuanChuException("售后订单地址添加失败");
                }
            }else {
                orderRefundAddress.setOrderRefundId(orderRefundId);
                BeanUtils.copyProperties(storeAddress, orderRefundAddress);
                orderRefundAddress.setCreateTime(String.valueOf(Instant.now().toEpochMilli() / 1000));
                boolean save = orderRefundAddressService.updateById(orderRefundAddress);

                if (!save) {
                    throw new YuanChuException("售后订单地址添加失败");
                }
            }

        }
        // 修改售后订单状态
        orderRefund.setAuditStatus(param.getForm().getAuditStatus());
        orderRefund.setStatus(param.getForm().getAuditStatus());
        String refuseDesc = param.getForm().getRefuseDesc();
        if (StringUtils.isNotEmpty(refuseDesc)){
            orderRefund.setRefuseDesc(refuseDesc);
        }
        orderRefund.setUpdateTime(String.valueOf(Instant.now().toEpochMilli() / 1000));
        boolean update = this.updateById(orderRefund);
        if (!update) {
            throw new YuanChuException("售后订单审核失败");
        }

        // 发送消息更改索引
        rabbitTemplate.convertAndSend(MqOrderConstants.ORDER_REFUND_EXCHANGE, MqOrderConstants.ORDER_INSERT_KEY, orderRefundId);
    }

    @Override
    @Transactional
    public void applyRefundOrderGoods(GoodsRefundParamsDto param, Integer userId) {
        YoshopOrderRefundEntity orderRefund = new YoshopOrderRefundEntity();
        YoshopOrderGoodsEntity orderGoods = orderGoodsService.getById(param.getOrderGoodsId());
        if (null == orderGoods){
            throw new YuanChuException("订单商品不存在");
        }
        orderRefund.setOrderId(orderGoods.getOrderId());
        orderRefund.setOrderGoodsId(orderGoods.getOrderGoodsId());
        orderRefund.setUserId(userId);
        orderRefund.setApplyDesc(param.getForm().getContent());
        orderRefund.setType(param.getForm().getType());
        orderRefund.setRefundMoney(orderGoods.getTotalPayPrice());
        orderRefund.setStoreId(10001);
        orderRefund.setCreateTime(String.valueOf(Instant.now().toEpochMilli()/1000));
        orderRefund.setUpdateTime(String.valueOf(Instant.now().toEpochMilli()/1000));
        boolean save = this.save(orderRefund);
        if (!save){
            throw new YuanChuException("申请售后失败");
        }
        List<Integer> images = param.getForm().getImages();
        if (images != null && !images.isEmpty()) {
            for (Integer image : images) {
                YoshopOrderRefundImageEntity imgEntity =  new YoshopOrderRefundImageEntity();
                imgEntity.setOrderRefundId(orderRefund.getOrderRefundId());
                imgEntity.setImageId(image);
                imgEntity.setStoreId(10001);
                imgEntity.setCreateTime(String.valueOf(Instant.now().toEpochMilli()/1000));
                int saveImg = orderRefundImageDao.insert(imgEntity);
                if (saveImg < 1){
                    throw new YuanChuException("申请售后失败");
                }
            }
        }
        // 发送消息更改索引
        rabbitTemplate.convertAndSend(MqOrderConstants.ORDER_REFUND_EXCHANGE, MqOrderConstants.ORDER_INSERT_KEY, orderRefund.getOrderRefundId());

    }

    @Override
    @Transactional
    public void refundOrderDelivery(OrderRefundParamsDto param, Integer userId) {
        Integer orderRefundId = param.getOrderRefundId();
        YoshopOrderRefundEntity orderRefund = this.getOne(new QueryWrapper<YoshopOrderRefundEntity>()
                .eq("order_refund_id", orderRefundId).eq("user_id", userId));
        if (orderRefund == null) {
            throw new YuanChuException("售后订单不存在");
        }
        orderRefund.setIsUserSend(1);
        orderRefund.setSendTime(String.valueOf(Instant.now().toEpochMilli()/1000));
        orderRefund.setExpressId(String.valueOf(param.getForm().getExpressId()));
        orderRefund.setExpressNo(param.getForm().getExpressNo());
        orderRefund.setUpdateTime(String.valueOf(Instant.now().toEpochMilli()/1000));
        boolean update = this.updateById(orderRefund);
        if (!update) {
            throw new YuanChuException("售后订单发货失败");
        }

        // 发送消息更改索引
        rabbitTemplate.convertAndSend(MqOrderConstants.ORDER_REFUND_EXCHANGE, MqOrderConstants.ORDER_INSERT_KEY, orderRefund.getOrderRefundId());


    }

    private void formatOrderRefund(YoshopOrderRefundEntity orderRefund) {
        // orderRefund.setCreateTime(DateFormatUtils.formatDatetime(orderRefund.getCreateTime()));
        orderRefund.setUpdateTime(DateFormatUtils.formatDatetime(orderRefund.getUpdateTime()));
        orderRefund.setOrderGoods(yoshopOrderService.queryOrderGoodsById(orderRefund.getOrderGoodsId()));
        // 商家审核状态(0待审核 10已同意 20已拒绝)
        Integer auditStatus = orderRefund.getAuditStatus();
        if (auditStatus == 0) {
            orderRefund.setStateText("等待审核中");
        } else if (auditStatus == 20) {
            orderRefund.setStateText("已拒绝");
        } else if (auditStatus == 10) {
            orderRefund.setStateText("已同意退货，请及时发货");
        }
    }
}
